//


import UIKit
import AVFoundation
import Photos

class WP_DailyAddViewController: WP_BasicViewController {
    
    var finishStr:String?       //完成
    var UnfinishedStr:String?   //未完成
    var summaryStr:String?      //总结
    var remarksStr:String?      //备注
    var model:DayModel?
    var pickImageController:UIImagePickerController?
    var footView:WP_PhotoView!
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavTitle("DailyAdd")
        // Do any additional setup after loading the view.
        isEmpty()
        self.view.addSubview(dTableView)
        setFootView()
         WP_CoreDataModel.coreDataManager.setEntityName(text: "DayModel")
    }
    func isEmpty() {
        if model != nil {
            imageArray = (model?.imgArray as? [UIImage])!
        }
    }
    
    lazy var dTableView:UITableView = {
        
        let tableview = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - kNavBarHeight), style: .plain)
        tableview.delegate = self
        tableview.dataSource = self
        tableview.rowHeight = kRatioHeight(100)
        tableview.tableFooterView = UIView()
        tableview .register(WP_FieldTableViewCell.classForCoder(), forCellReuseIdentifier:NSStringFromClass(WP_FieldTableViewCell.classForCoder()))
        tableview.separatorColor = UIColor.white
        return tableview
        
    }()
    //图片数组
    lazy var imageArray:[UIImage] = {
        let arr = Array<UIImage>()
        return arr
    }()
    
    //footview
    func setFootView()  {
        
        let foot = WP_FootView(frame: CGRect(x: 0, y: kScreenHeight-kTabBarHeight, width: kScreenWidth, height: kTabBarHeight))
        self.view.addSubview(foot)
        weak var weakSelf = self
        foot.FootBlock = {
            
            if weakSelf!.finishStr?.count == 0 ||  weakSelf!.UnfinishedStr?.count == 0 || weakSelf!.summaryStr?.count == 0 {
                return
            }
            var dic = Dictionary<String,Any>()
            //            let dic2 = Dictionary<String,Any>()
            
            let dateformatter = DateFormatter()
            dateformatter.dateFormat = "YYYY-MM-dd HH:mm"// 自定义时间格式
            let time = dateformatter.string(from: Date())
            //
            dic.updateValue(weakSelf!.finishStr ?? "", forKey: "finish")
            dic.updateValue(weakSelf!.UnfinishedStr ?? "", forKey: "unfinish")
            dic.updateValue(weakSelf!.summaryStr ?? "", forKey: "summary")
            dic.updateValue(weakSelf!.remarksStr ?? "", forKey: "remark")
            dic.updateValue(weakSelf!.imageArray, forKey: "imgArray")
            
            if weakSelf!.model == nil {//添加
                
                dic.updateValue(time, forKey: "date")
                dic.updateValue(weakSelf!.randomNum(), forKey: "iD")
                
                 WP_CoreDataModel.coreDataManager.saveData(parameter: dic, success: { weakSelf?.navigationController?.popViewController(animated: true)}, fail: {})
                
            }else {//修改
                
                 WP_CoreDataModel.coreDataManager.updateData(parameter: dic, key: "iD=\(weakSelf!.model?.iD! ?? "")", success: { weakSelf?.navigationController?.popViewController(animated: true)}, fail: {})
                
            }
        }
    }
    
    
}

extension WP_DailyAddViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:WP_FieldTableViewCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(WP_FieldTableViewCell.classForCoder()), for: indexPath) as! WP_FieldTableViewCell
        cell.index = indexPath.row
        cell.selectionStyle = .none
        cell.delegate = self;
        if indexPath.row == 0 {
            cell.titleLabel.text = "Work done today"
            cell.tfield.placeholder = "Input a Work done today"
            cell.tfield.text = model?.finish
            finishStr = model?.finish ?? ""
            
        }else if indexPath.row == 1 {
            cell.titleLabel.text = "Unfinished business today"
            cell.tfield.placeholder = "Input a Unfinished business today"
            cell.tfield.text = model?.unfinish
            UnfinishedStr = model?.unfinish ?? ""
            
        }else if indexPath.row == 2 {
            cell.titleLabel.text = "Job summary"
            cell.tfield.placeholder = "Input a Job summary"
            cell.tfield.text = model?.summary
            summaryStr = model?.summary ?? ""
            
        }else if indexPath.row == 3 {
            cell.titleLabel.text = "Remarks"
            cell.tfield.placeholder = "Input a Remarks"
            cell.tfield.text = model?.remark
            remarksStr = model?.remark ?? ""
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 200
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        footView = WP_PhotoView()
        footView.backgroundColor = UIColor.white
        footView.delegate = self
        footView.reloadData(arr: imageArray)
        if imageArray.count >= 4 {
            footView.btn.isHidden = true
        }
        return footView
    }
}

//cell Delegate
extension WP_DailyAddViewController:WP_FieldTableViewDelegate {
    
    func SendIndexCell(index: NSInteger, obj: String) {
        switch index {
        case 0:
            finishStr = obj
        case 1:
            UnfinishedStr = obj
        case 2:
            summaryStr = obj
        case 3:
            remarksStr = obj
        default: break
            
        }
    }
    
}
//foot delegate
extension WP_DailyAddViewController:WP_PhotoViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func updateloading() {
        
        weak var weakSelf = self
        pickImageController = UIImagePickerController.init()
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
            
            //获取相册权限
            PHPhotoLibrary.requestAuthorization({ (status) in
                switch status {
                case .notDetermined: break
                    
                case .restricted://此应用程序没有被授权访问的照片数据
                    break
                case .denied://用户已经明确否认了这一照片数据的应用程序访问
                    break
                case .authorized://已经有权限
                    weakSelf!.pickImageController!.delegate=self
                    weakSelf!.pickImageController!.allowsEditing = true
                    weakSelf!.pickImageController!.sourceType = UIImagePickerController.SourceType.photoLibrary;
                    //                    weakSelf?.pickImageController?.mediaTypes=[kUTTypeMovie as String]//只有视频
                    //                 weakSelf?.pickImageController?.mediaTypes=[kUTTypeImage as String]//只有照片
                    weakSelf?.pickImageController?.mediaTypes=UIImagePickerController.availableMediaTypes(for: UIImagePickerController.SourceType.photoLibrary)!//包括照片和视频
                    //弹出相册页面或相机
                    self.present( weakSelf!.pickImageController!, animated: true, completion: {
                    })
                    
                    break
                }
            })
        }
    }
    
    //选中图片，保存图片或视频到系统相册
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        let image = (info[UIImagePickerController.InfoKey.editedImage] as! UIImage)
        
        /*
         var image: UIImage?
         let typ:String = (info[UIImagePickerController.InfoKey.mediaType]as!String)//类型
         // 图片类型"public.image"
         if typ == "public.image"{
         if(picker.allowsEditing){
         //裁剪后图片
         image=(info[UIImagePickerController.InfoKey.editedImage] as! UIImage)
         }else{
         //原始图片
         image=(info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
         }
         
         }
         */
        self.imageArray.append(image)
        footView.reloadData(arr: imageArray)
        
        if imageArray.count >= 4 {
            footView.btn.isHidden = true
        }
        
        
        
        //关闭当前界面
        self.dismiss(animated: true, completion: nil)
    }
    
}
